<template>
    <div class="title">
        店铺管理
        <el-button type="primary" style="float: right; 
            margin-right: 10px; margin-top:10px; 
            " @click="saveShopInfo">
            保存店铺信息
        </el-button>
    </div>
    <el-form :data="shopInfo" label-width="80px" style="width: 100%">
        <el-form-item label="店铺名称">
            <el-input v-model="shopInfo.name" placeholder="请输入店铺名称" />
        </el-form-item>
        <el-form-item label="店铺公告">
            <el-input v-model="shopInfo.bulletin" placeholder="请输入店铺公告" type="textarea" :rows="2" />
        </el-form-item>
        <div class="avater">
            <span>店铺头像</span>
            <el-upload class="avatar-uploader" :action="serveUrl + '/shop/upload'" :show-file-list="false"
                :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                <img v-if="imageUrl" :src="serveUrl + imageUrl" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon">
                    <Plus />
                </el-icon>
            </el-upload>
        </div>
        <div class="img">
            <span>店铺图片</span>
            <el-upload 
    :file-list="fileList" 
    :action="serveUrl + '/shop/upload'" 
    list-type="picture-card"
    :on-preview="handlePictureCardPreview" 
    :on-remove="handleRemove"
    :on-success="handlePictureSuccess"
>
    <el-icon><Plus /></el-icon>
</el-upload>

            <el-dialog v-model="dialogVisible">
                <img w-full :src="dialogImageUrl" alt="Preview Image" />
            </el-dialog>
        </div>

        <el-form-item label="配送费">
            <el-input v-model="shopInfo.deliveryPrice" placeholder="请输入配送费" />
        </el-form-item>
        <el-form-item label="送达时间">
            <el-input v-model="shopInfo.deliveryTime" placeholder="请输入送达时间" />
        </el-form-item>
        <el-form-item label="描述">
            <el-input v-model="shopInfo.description" placeholder="请输入描述" />
        </el-form-item>
        <el-form-item label="评分">
            <el-input v-model="shopInfo.score" placeholder="请输入评分" />
        </el-form-item>
        <el-form-item label="销量">
            <el-input v-model="shopInfo.sellCount" placeholder="请输入销量" />
        </el-form-item>

        <div class="supports">
            <span>活动支持</span>
            <el-checkbox-group v-model="shopInfo.supports">
                <el-checkbox v-for="(item, index) in supports" :key="index" :label="item.label" size="small" />
            </el-checkbox-group>
        </div>

        <div class="demo-range">
            <span>营业时间</span>
            <el-time-picker v-model="shopInfo.date" is-range range-separator="至" start-placeholder="开始时间"
                end-placeholder="结束时间" style="width: 300px" />
        </div>

        <el-form-item label="起送价格">
            <el-input v-model="shopInfo.minPrice" placeholder="请输入起送价格" />
        </el-form-item>
    </el-form>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { serveUrl } from '../../utils/common'
import { getShopInfo, updateShopInfo } from '../../api/account'
import dayjs from 'dayjs'

const shopInfo = ref({
    id: null,
    name: '',
    bulletin: '',
    avatar: '',
    pics: [],
    deliveryPrice: null,
    deliveryTime: null,
    description: '',
    score: '',
    sellCount: null,
    supports: [],
    date: [],  // 先初始化为空数组
    minPrice: ''
})

const supports = ref([
    {
        label: '单人精彩套餐',
        value: 'single'
    },
    {
        label: 'VC无限橙果汁全场8折',
        value: 'discount'
    },
    {
        label: '在线支付满28减5',
        value: 'jian'
    },
    {
        label: '特价饮品八折抢购',
        value: 'tejia'
    },
    {
        label: '中秋特惠',
        value: 'zhongqiu'
    },
    {
        label: '国庆特价',
        value: 'guoqing'
    },
    {
        label: '春节1折折扣',
        value: 'chunjie'
    }
])

const fileList = ref([])
const dialogVisible = ref(false)
const dialogImageUrl = ref('')
const imageUrl = ref('')

// 获取店铺详情
const getShopDetails = async () => {
    try {
        const response = await getShopInfo();
        shopInfo.value = response.data;
        console.log(shopInfo.value);

        // 处理 avatar
        imageUrl.value = shopInfo.value.avatar;
        const lastIndex = shopInfo.value.avatar.lastIndexOf('/');
        shopInfo.value.avatar = lastIndex !== -1 ? shopInfo.value.avatar.slice(lastIndex + 1) : shopInfo.value.avatar;
        shopInfo.value.supports = response.data.supports || [];

        // 处理 pics
        if (typeof shopInfo.value.pics === 'string') {
            try {
                shopInfo.value.pics = JSON.parse(shopInfo.value.pics.replace(/'/g, '"'));
            } catch (error) {
                console.error('解析 pics 失败:', error);
                shopInfo.value.pics = [];
            }
        }
        if (!Array.isArray(shopInfo.value.pics)) {
            shopInfo.value.pics = [];
        }

        fileList.value = shopInfo.value.pics.map(pic => {
            const lastIndex = pic.lastIndexOf('/');
            const name = lastIndex !== -1 ? pic.slice(lastIndex + 1) : pic;
            return {
                name,
                url: serveUrl + pic
            };
        });
        console.log(fileList.value);

        // 处理 supports
        if (typeof shopInfo.value.supports === 'string') {
            try {
                shopInfo.value.supports = JSON.parse(shopInfo.value.supports.replace(/'/g, '"'));
            } catch (error) {
                console.error('解析 supports 失败:', error);
                shopInfo.value.supports = [];
            }
        }
        if (!Array.isArray(shopInfo.value.supports)) {
            shopInfo.value.supports = [];
        }

        // 处理 date
        if (Array.isArray(shopInfo.value.date) && shopInfo.value.date.length === 2) {
            shopInfo.value.date = shopInfo.value.date.map(dateStr => {
                if (typeof dateStr === 'string') {
                    return new Date(dateStr);
                }
                return dateStr;
            });
        } else {
            const defaultStartTime = new Date()
            defaultStartTime.setHours(8, 0, 0)
            const defaultEndTime = new Date()
            defaultEndTime.setHours(22, 30, 0)
            shopInfo.value.date = [defaultStartTime, defaultEndTime];
        }
    } catch (error) {
        console.error('获取店铺详情失败:', error);
        ElMessage.error('获取店铺详情失败');
    }
};

// 保存店铺信息
const saveShopInfo = async () => {
    try {
        const formData = {
            id: shopInfo.value.id,
            name: shopInfo.value.name,
            bulletin: shopInfo.value.bulletin,
            avatar: shopInfo.value.avatar,
            // 只取文件名并转换为字符串数组
            pics: JSON.stringify(fileList.value.map(file => file.name)),
            deliveryPrice: shopInfo.value.deliveryPrice,
            deliveryTime: shopInfo.value.deliveryTime,
            description: shopInfo.value.description,
            score: shopInfo.value.score,
            sellCount: shopInfo.value.sellCount,
            // 转换为字符串数组
            supports: JSON.stringify(shopInfo.value.supports),
            // 格式化日期并转换为字符串数组
            date: JSON.stringify(shopInfo.value.date.map(date =>
                dayjs(date).format('YYYY-MM-DD HH:mm:ss')
            )),
            minPrice: shopInfo.value.minPrice
        };
        console.log('保存前的formData:', formData);
        const response = await updateShopInfo(formData);
        ElMessage.success('保存成功');
        getShopDetails();
    } catch (error) {
        console.error('保存失败:', error);
        ElMessage.error('保存失败');
    }
};


// 处理头像上传成功
const handleAvatarSuccess = (res, file) => {
    console.log(res);
    
    if (res.code == 0) {
        imageUrl.value = res.imgUrl;
        console.log(res.imgUrl);
        
        const lastIndex = res.imgUrl.lastIndexOf('/');
        shopInfo.value.avatar = lastIndex !== -1 ? res.imgUrl.slice(lastIndex + 1) : res.imgUrl;
        console.log(shopInfo.value.avatar);
        
    } else {
        ElMessage.error(res.msg);
    }
}

// 处理图片上传成功
const handlePictureSuccess = (res, uploadFile) => {
    console.log(res);
    if (res.code == 0) {
        const lastIndex = res.imgUrl.lastIndexOf('/');
        const fileName = lastIndex !== -1 ? res.imgUrl.slice(lastIndex + 1) : res.imgUrl;
        // 手动添加新的文件项到 fileList
        fileList.value.push({
            name: fileName,
            url: serveUrl + res.imgUrl // 显示完整路径
        });
    } else {
        ElMessage.error(res.msg);
    }
}

// 处理图片上传失败
// 处理头像上传前
const beforeAvatarUpload = (rawFile) => {
    if (rawFile.type !== 'image/jpeg') {
        ElMessage.error('Avatar picture must be JPG format!');
        return false;
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('Avatar picture size can not exceed 2MB!');
        return false;
    }
    return true;
}

// 处理图片预览
const handlePictureCardPreview = (file) => {
    dialogImageUrl.value = file.url;
    dialogVisible.value = true;
}

// 处理图片删除
const handleRemove = (file) => {
    const index = fileList.value.indexOf(file);
    fileList.value.splice(index, 1);
}

// 判断是否选中
const isChecked = (label) => {
    return shopInfo.value.supports.includes(label);
}

// 组件挂载时获取店铺详情
onMounted(() => {
    getShopDetails();
})
</script>

<style lang="scss" scoped>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}

.title {
    width: 100%;
    height: 50px;
    font-size: 20px;
    color: #333;
    line-height: 50px;
    padding-left: 20px;
    text-align: left;
    border-bottom: 1px solid #dcdfe6;
}

.avater {
    display: flex;
    align-items: center;

    span {
        color: #606266;
        font-size: 14px;
        margin-left: 10px;
        padding-right: 12px;
    }
}

.img {
    display: flex;
    align-items: center;

    span {
        color: #606266;
        font-size: 14px;
        margin-left: 10px;
        padding-right: 12px;
    }
}

.supports {
    display: flex;
    align-items: center;
    height: 50px;

    span {
        color: #606266;
        font-size: 14px;
        margin-left: 10px;
        padding-right: 12px;
    }
}

.demo-range {
    display: flex;
    align-items: center;
    height: 50px;
    width: 400px;

    span {
        color: #606266;
        font-size: 14px;
        margin-left: 10px;
        padding-right: 12px;
    }
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>